/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.superduperbudget.central.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import se.superduperbudget.central.core.EMF;
import se.superduperbudget.central.db.SuperDuperBank;
import se.superduperbudget.central.db.SuperDuperUser;
import se.superduperbudget.central.db.SuperDuperUserBank;

/**
 *
 * @author Emil
 */
@WebServlet(name = "GenerateBanks", urlPatterns = {"/GenerateBanks"})
public class GenerateBanks extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // Fills the db with banks
        EntityManager em = EMF.get().createEntityManager();
        
        File dir = new File(getServletContext().getRealPath("WEB-INF/banks"));
        
        Map<String, File> icons = new HashMap<String, File>();
        
        for(File child : dir.listFiles()) {
            if (child.getName().endsWith(".png")) {
                icons.put(child.getName(), child);
            }
        }
        
        SuperDuperBank swedbank = null;
        
        for (File child : dir.listFiles()) {
            if (child.isFile() && child.getName().endsWith(".txt")) {
                String code = FileUtils.readFileToString(child);
                Matcher classMatcher = Pattern.compile("class(.*?)(extends|implements|\\{)").matcher(code);

                String name;
                if (classMatcher.find())
                    name = classMatcher.group(1).trim();
                else name = "Test";
                
                SuperDuperBank bank = new SuperDuperBank();
                bank.setName(name);
                bank.setCode(code);
                
                if (name.equals("Swedbank"))
                    swedbank = bank;
                
                String iconName = "logo_" + child.getName().toLowerCase()
                            .substring(0, child.getName().length() - 4)
                            + ".png";
                
                File icon = icons.get(iconName);
                
                if(icon == null) {
                    icon = icons.get("logo_unknown_app.png");
                }
                
                bank.setIcon(FileUtils.readFileToByteArray(icon));
                
                EntityTransaction tx = em.getTransaction();
                tx.begin();
                em.persist(bank);
                tx.commit();
            }
        }
        
        SuperDuperUser u = new SuperDuperUser();
        u.setfName("Emil");
        u.setlName("Andersson");
        u.setEmail("emil@klargodut.com");
        u.setPassword("e03ae33ee8417ce2c9785274217636e0");
        u.setUsername("emil");
        u.setUuid("1");
        
        ArrayList<SuperDuperUserBank> ubs = new ArrayList<SuperDuperUserBank>();
        SuperDuperUserBank ub = new SuperDuperUserBank();
        ub.setBank(swedbank);
        ub.setUsername("xxxxxx-xxxx");
        ub.setPassword("xxxxxx");
        
        u.setUserBanks(ubs);
        
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.persist(u);
        em.persist(ub);
        tx.commit();
        
        em.close();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
